#include <stdlib.h>
#include "buzzer_porting.h"
#include "gd32f10x.h"                   // Device header

#define BUZZER_TASK_PERIOD 30
#define BUZZER_PORT         GPIOA
#define BUZZER_PIN          GPIO_PIN_12

/* 全系统全局变量 */
BuzzerObjectTypeDef buzzer[1];
static BuzzerCtrlTypeDef buzzer1_ctrl_ququeHandle; /* 蜂鸣器控制队列Handle */

static void buzzer1_set_pwm(BuzzerObjectTypeDef *self, uint32_t freq, uint32_t duty);         /* pwm设置接口 */
static int put_ctrl_block(BuzzerObjectTypeDef *self, BuzzerCtrlTypeDef *p);   /* 控制入队接口 */
static int get_ctrl_block(BuzzerObjectTypeDef *self, BuzzerCtrlTypeDef *p);   /* 控制出队接口 */


/**
  * @brief 蜂鸣器相关的初始化
  * @retval None.
  *
*/
void buzzer_init(void)
{
	buzzer_object_init(&buzzer[0]);
	buzzer[0].id = 1;
    buzzer[0].set_pwm = buzzer1_set_pwm;
	buzzer[0].get_ctrl_block = get_ctrl_block;
	buzzer[0].put_ctrl_block = put_ctrl_block;
}


/**
  * @brief 系统定时器回调
  * @detials 定时刷新LED灯状态，定时时间通过 CubeMx 设置
  * @retval None.
  *
*/
void buzzer_timer_callback(void *argument)
{
    buzzer_task_handler(&buzzer[0], BUZZER_TASK_PERIOD);
}


/**
  * @brief 蜂鸣器 PWM 设置接口
  * @param freq PWM 频率
  * @retval None.
  *
*/
static void buzzer1_set_pwm(BuzzerObjectTypeDef *self, uint32_t freq, uint32_t duty)
{
	if (duty == 0)
    {
        gpio_bit_write(BUZZER_PORT, BUZZER_PIN, 0);
    }
    else
    {
        gpio_bit_write(BUZZER_PORT, BUZZER_PIN, 1);
    }
}

static int8_t simulateQueuePut(BuzzerCtrlTypeDef *self, BuzzerCtrlTypeDef *p)
{
    self->data_effective = 1;
    self->freq = p->freq;
    self->duty = p->duty;
    self->repeat = p->repeat;
    self->ticks_on = p->ticks_on;
    self->ticks_off = p->ticks_off;
    return 0;
}

static int8_t simulateQueueGet(BuzzerCtrlTypeDef *self, BuzzerCtrlTypeDef *p)
{
    if (self->data_effective == 0)
    {
        return -1;
    }
    self->data_effective = 0;
    p->freq = self->freq;
    p->duty = self->duty;
    p->repeat = self->repeat;
    p->ticks_on = self->ticks_on;
    p->ticks_off = self->ticks_off;
    return 0;
}
/**
  * @brief 蜂鸣器控制队列入队接口
  * @param p 要出队的控制参数结构体指针
  * @retval 0 成功
  * @retval !=0 失败 
  *
*/
static int put_ctrl_block(BuzzerObjectTypeDef *self, BuzzerCtrlTypeDef *p) {
	return (int)simulateQueuePut(&buzzer1_ctrl_ququeHandle, p);
}

/**
  * @brief 蜂鸣器控制队列出队接口
  * @param  出队数据的存储指针
  * @retval 0 成功
  * @retval !=0 失败 
  *
*/
static int get_ctrl_block(BuzzerObjectTypeDef *self, BuzzerCtrlTypeDef *p) {
	return (int)simulateQueueGet(&buzzer1_ctrl_ququeHandle, p);
}


